/**
 * Created by rockyren on 14/11/29.
 */
cartApp.controller('cartIndexController',['$scope','cartServices',function($scope,cartServices){

  /**
   * 数量计数器,使用闭包实现
   * @param aId: 对应的商品id
   * @param aAmount
   * @param aCount
   * @returns {{minus: Function, plus: Function, getCount: Function}}
   */

  function countHandle(aId,aAmount,aCount,aPrice) {
    var id = aId;
    var count = aCount;
    var amount = aAmount;
    var price = aPrice;

    return {
      minus: function() {
        console.log('minus');
        if(count > 1) {
          count--;
          //每修改一次count就发一次请求
          requestCount(id,count);
          $scope.total -= price;
        }
      },
      plus: function() {
        if(count < amount) {
          count++;
          requestCount(id,count);
          $scope.total += price;
        }
      },
      getCount: function() {
        return count;
      }
    }
  }

  /**
   * 请求修改对应商品的数量
   * @param id
   * @param count
   */
  function requestCount(id,count) {
    cartServices.update(id,{
      count: count
    })
      .success(function(data){

      })
      .error(function(data){
        console.log(data.error);
      })
  }



  function loadCart(){
    cartServices.get()
      .success(function(data){

        $scope.cartList = data;
        $scope.total = 0;

        /**
         * 往cartList添加属性Number--计数器
         * 使cartList变成[{"id",...,"amount","Number"}]
         */

        $scope.Numbers = {};
        //$scope.productStatus = {};
        //$scope.allStatus = false;

        for(var i=0;i<$scope.cartList.length;i++) {
          var curCart = $scope.cartList[i];
          var curCountHandle = countHandle(curCart.id,curCart.amount,curCart.count,curCart.price);
          $scope.Numbers[curCart.id] = curCountHandle;

          //设置总计
          $scope.total += curCart.count * curCart.price;
          //$scope.productStatus[curCart.id] = false;
        }
      }).error(function(data){
        console.log(data.error);
      });
  }
  loadCart();




  $scope.delete = function(id){
    cartServices.destroy(id)
      .success(function(data){
        console.log('删除成功');
        loadCart();
      })
      .error(function(data){
        console.log(data.error);
      });
  };







}]);